import axios from 'axios'

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8001'

export interface WidgetCreateRequest {
  name: string
  version: string
  description?: string
  category?: string
  config_schema?: string
  api_endpoints?: string
  frontend_files?: string
}

export interface WidgetUpdateRequest {
  name?: string
  version?: string
  description?: string
  category?: string
  config_schema?: string
  api_endpoints?: string
  frontend_files?: string
  is_active?: boolean
}

export interface UserWidgetCreateRequest {
  widget_id: number
  config_data?: string
}

export class WidgetService {
  private api = axios.create({
    baseURL: `${API_BASE_URL}/api`,
    timeout: 10000
  })

  // 组件管理
  async getWidgets(params?: {
    page?: number
    pageSize?: number
    search?: string
    category?: string
  }) {
    const response = await this.api.get('/widgets/', { params })
    return response.data
  }

  async getWidget(id: number) {
    const response = await this.api.get(`/widgets/${id}`)
    return response.data
  }

  async createWidget(data: WidgetCreateRequest) {
    const response = await this.api.post('/widgets/', data)
    return response.data
  }

  async updateWidget(id: number, data: WidgetUpdateRequest) {
    const response = await this.api.put(`/widgets/${id}`, data)
    return response.data
  }

  async deleteWidget(id: number) {
    await this.api.delete(`/widgets/${id}`)
  }

  async uploadWidget(file: File) {
    const formData = new FormData()
    formData.append('file', file)
    
    const response = await this.api.post('/widgets/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    return response.data
  }

  // 用户组件管理
  async getUserWidgets() {
    const response = await this.api.get('/widgets/my/widgets')
    return response.data
  }

  async addUserWidget(data: UserWidgetCreateRequest) {
    const response = await this.api.post('/widgets/my/widgets', data)
    return response.data
  }

  async updateUserWidget(id: number, configData: string) {
    const response = await this.api.put(`/widgets/my/widgets/${id}`, null, {
      params: { config_data: configData }
    })
    return response.data
  }

  async deleteUserWidget(id: number) {
    await this.api.delete(`/widgets/my/widgets/${id}`)
  }

  // 组件分类
  async getWidgetCategories() {
    const response = await this.api.get('/widgets/categories/list')
    return response.data
  }

  // 已加载组件
  async getLoadedWidgets() {
    const response = await this.api.get('/widgets/loaded')
    return response.data
  }
}

export const widgetService = new WidgetService()